import { Body, Controller, Get, Post, Res, HttpStatus, UploadedFile, UseInterceptors, HttpException, Query, Request } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { WxUser } from './wxUser.entity';
import { WxUserService } from './wxUser.service';
import { ValidTokenInterceptor } from '../../interceptor/validToken'
const xss = require('xss')

import {
  get,
  post
} from 'request'
import request from 'request'

import {join, resolve} from 'path'
import { createWriteStream } from 'fs';
import {
  wx_appid,
  wx_secret,
  wx_api,
  wx_open_api,
  wx_public_params_list,
  wx_appid_yz_zuozhedua,
  wx_secret_yz_zuozhedua,
  wx_appid_video_library,
  wx_secret_video_library,
  system_wx_user,
  video_VideoTimeout,
  video_RefererKey
} from '../../setting'
import {
  existsSync,
  mkdirSync
} from 'fs'
import {
  apibefore
} from '../../router'
import { ValidRSAInterceptor } from 'src/interceptor/validRSA';
import { WXAPI } from 'src/common/wx_api';
import { WxUserOpenIdService } from '../wxUserOpenId/wxUserOpenId.service';
import utils from 'src/common/utils';
import SMS from 'src/common/sms';
import { profitEnum } from '../profit/profit.enum';
import { RedisCacheService } from '../redisCache/redisCache.service';
@Controller(apibefore('/wxUser'))
export class WxUserController {
  constructor(private readonly wxUserService: WxUserService,
    private readonly wxUserOpenIdService: WxUserOpenIdService,
    private readonly redisCacheService: RedisCacheService,
  ) {}

  
  @Post('/sendSMS')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async sendSMS(@Body() data, @Request() req){
    try{
      return await SMS.send(data.phone)
    }catch(err) {
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  
  @Post('/phoneLogin')
  @UseInterceptors(ValidRSAInterceptor)
  async phoneLogin(@Body() userParams: { validCode: string, phone: string }, @Request() req) {
    try{
      return await this.wxUserService.phoneLogin(userParams.phone, userParams.validCode, req.headers.wx_user)
    }catch(err) {
      return new HttpException(err, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  @Post('/unionIdLogin')
  @UseInterceptors(ValidRSAInterceptor)
  async unionIdLogin(@Body() userParams: { unionid: string }, @Request() req) {
    let save = (id, openid, phone, name, resolve) => {
      let returnData = {
        id:id,
        phone:phone,
        wx_user:openid,
        name:name,
      }
      resolve(returnData)
    }
    return new Promise(async (resolve,reject) => {
      let result = {
        unionid: userParams.unionid
      }
      if(result.unionid){
        let wxUser = new WxUser()
        wxUser.create_time = new Date()
        wxUser.openid = result.unionid
        let wxInfo:WxUser = await this.wxUserService.findOne_By_OpenId(wx_appid_yz_zuozhedua, result.unionid)
        wxInfo = wxInfo[0]
        if(!wxInfo){
          reject(new HttpException('登录失败，找不到您的用户信息', HttpStatus.OK))
        }else if(wxInfo?.id){
          //查找当前用户是否用过当前小程序了
          let userOpenId = await this.wxUserOpenIdService.findOpenId(wx_appid_yz_zuozhedua, wxInfo.openid)
          if(userOpenId?.openid){
            save(wxInfo.id,wxInfo.openid, wxInfo.phone,wxInfo.name, resolve)
          }else{
            reject(new HttpException('登录失败，找不到您的用户信息，请重新获取unionId', HttpStatus.OK))
          }
        }else{
          reject(new HttpException('用户授权失败，获取 openid 失败', HttpStatus.OK))
        }
      }else{
        reject(new HttpException('用户授权失败', HttpStatus.OK))
      }
       
    })
  }

  @Post('/codeLogin')
  @UseInterceptors(ValidRSAInterceptor)
  async codeLogin(@Body() userParams: { login_code: string }, @Request() req) {
    let save = (id, id_card, openid, phone, name, resolve) => {
      let returnData = {
        id:id,
        phone:phone,
        wx_user:openid,
        name:name,
        id_card:id_card
      }
      resolve(returnData)
    }
    return new Promise(async (resolve,reject) => {
      let result = {
        login_code: userParams.login_code
      }
      if(result.login_code){
        let wxInfo:WxUser = await this.wxUserService.findOne_By_LoginCode(wx_appid_yz_zuozhedua, result.login_code)
        wxInfo = wxInfo[0]
        if(!wxInfo){
          reject(new HttpException('登录失败，找不到您的用户信息', HttpStatus.OK))
        }else if(wxInfo?.id){
          //查找当前用户是否用过当前小程序了
          let userOpenId = await this.wxUserOpenIdService.findOpenId(wx_appid_yz_zuozhedua, wxInfo.openid)
          if(userOpenId?.openid){
            save(wxInfo.id, wxInfo.id_card, wxInfo.openid, wxInfo.phone,wxInfo.name, resolve)
          }else{
            reject(new HttpException('登录失败，找不到您的用户信息，请重新获取login_code', HttpStatus.OK))
          }
        }else{
          reject(new HttpException('用户授权失败，获取 openid 失败', HttpStatus.OK))
        }
      }else{
        reject(new HttpException('用户授权失败', HttpStatus.OK))
      }
       
    })
  }




  @Get('/generatescheme')
  async generateScheme(@Query() params, @Request() req){
    //先临时进入登录小程序
    // return await new WXAPI().generatescheme(params.query)
    return await new WXAPI().generatescheme_yz_zuozheduan(params.query)
  }

  @Get('/generatescheme_yz_zuozheduan')
  async generatescheme_yz_zuozheduan(@Query() params, @Request() req){
    return await new WXAPI().generatescheme_yz_zuozheduan(params.query)
  }


  @Get('/findByName')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async findByName(@Query() params, @Request() req){
    let { skip, take } = utils.getLimit(params.pageSize, params.pageIndex)
    return await this.wxUserService.findByName(req.headers.wx_user, params.keyword, skip, take)
  }

    
  @Get('/search')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async Search(@Query() params, @Request() req){
    let { skip, take } = utils.getLimit(params.pageSize, params.pageIndex)
    return await this.wxUserService.search(req.headers.wx_user, params.keyword, skip, take)
  }
    

  /**
   * 设置视频答案
   * @param wx_user
   * @param videoList
   */
  setVideoAnswer(wx_user: string, videoList: any, answerList: any, multiImg: any, rewardAnswerList?: any){
    rewardAnswerList = rewardAnswerList || []
    videoList.map((e:any) => {
      let findAnswerList = answerList.filter(c => c.video_id == e.id)
      //视频审核通过的答案编号
      let findOKAnswher = findAnswerList.find(c => c.check == 1)
      e.check_answer = findOKAnswher?.answer_id
      //是否有驳回的答案
      if(!e.check_answer && findAnswerList.find(c => utils.judeAnswerIsReject(c))){
        e.check_answer = 0
      }
      //审核中的答案
      e.is_answer = findAnswerList.find(c => c.check != 1 && c.check !== 0 && c.wx_user == wx_user)?.wx_user
      //自己的所有答案
      e.is_answer_history = findAnswerList.find(c => c.wx_user == wx_user && !(c.type == 2 && c.check == 0)) ? true : false
      if(e.is_answer_history && e.original == 0 && findAnswerList.find(c => c.check == 1 && c.wx_user == e.video_author && c.wx_user == wx_user)){
        e.is_answer_history = false
      }
      //自己回答审核通过，或者自己产生利润（返回答案）
      let nowTime = new Date().getTime()
      let findAnswerResult = findAnswerList.filter(c => c.check == 1 && (c.wx_user == wx_user || (c.profit_status != profitEnum.refoundSuccess && c.answer_id && c.use_wx_user == wx_user)))
      if(findAnswerResult.length > 0){
        e.is_profit_result = true
      }
      //答案作者是我自己
      if(findAnswerList.find(c => c.check == 1 && c.wx_user == wx_user)){
        e.answer_author_is_me = true
      }else{
        //答案是否被驳回
        //1、不存在审核中
        //2、被拒绝
        let now = new Date().getTime()
        if(!e.is_answer && findAnswerList.find(c => (c.check == 0) && c.wx_user === wx_user)){
          e.answer_is_me_reject = true
        }
      }
      //自己回答审核通过，或者自己产生利润（返回多图）
      e.multi_img = multiImg.filter(c => c.video_id == e.id && ((c.check == 1 && c.wx_user == wx_user) || (c.answer_id && c.use_wx_user == wx_user)) && c.multi_img).map(c => c.multi_img)
      if(e.multi_img.length === 0){
        delete e.multi_img
      }
      // e.multi_img_count = multiImg.filter(c => c.video_id == e.id).length

      let findProfit = findAnswerList.find(c => (c.check == 1 && c.wx_user == wx_user) || (c.answer_id && c.use_wx_user == wx_user && (c.profit_status == 0 || c.profit_status == 1 || c.profit_status == 3)))
      e.profit_works = findProfit?.id
      e.profit_status = findProfit?.profit_status
      if(e.video_author == wx_user){
        e.author = true
      }
      e.author_answer = findAnswerList.find(e => e.wx_user == wx_user && e.type != 2) ? true : false
      if(e.video_author === system_wx_user && e.video_author === wx_user){
        e.system_wx_user = true
      }
      if(wx_user === system_wx_user){
        e.is_system_user = true
      }
      delete e.video_author
      //悬赏的作品有答案了
      if(rewardAnswerList.find(c => c.wx_user == wx_user && c.video_id == e.id)){
        e.rewardIsAnswer = true
      }
      if(e.wx_user_source === wx_user){
        e.author_source = true
      }
      delete e.wx_user_source
    })
  }

  getPlayVideoUrl(currentVideo){
    let oldurl:any = currentVideo.video_url || ''
    let https = 'https://'
    let http = 'http://'
    if(oldurl.indexOf(https) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(https) + https.length)
    }else if(oldurl.indexOf(http) > -1){
      oldurl = oldurl.substring(oldurl.indexOf(http) + http.length)
    }
    oldurl = oldurl.split('/')
    oldurl = oldurl.slice(1,oldurl.length - 1)
    let endTime:string = parseInt((new Date().getTime() / 1000 + video_VideoTimeout).toString()).toString(16)
    let sign = utils.md5(video_RefererKey + '/' + oldurl.join('/') + '/' + endTime)
    if(currentVideo.video_url){
      let newurl = currentVideo.video_url + '?t=' + endTime + '&sign=' + sign
      currentVideo.video_url = newurl
    }
  }

  @Get('/findInfo')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async findInfo(@Query() params, @Request() req){
    let wx_user = req.headers.wx_user
    let result = await this.wxUserService.findInfo(wx_user, params.id, params.ic_group, params.unconcern_id) 
    this.setVideoAnswer(wx_user, result.videos, result.answerList, result.multiImg)
    result.videos.map(currentVideo => {
      this.getPlayVideoUrl(currentVideo)
    })
    return {info:result.info, videos:result.videos}
  }

  
  @Get('/findIcInfo')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async findIcInfo(@Query() params, @Request() req){
    let wx_user = req.headers.wx_user
    let cacheKey = `${wx_user}:icinfo:`
    let cacheKeyIcInfo = `icinfo:`
    let cacheKeyPlatform = `icinfo:`
    let cacheKeyVideos = `${wx_user}:icinfo:`
    if(params.id){
      cacheKey = cacheKey + 'wxuser:' + params.id + ':concern'
      cacheKeyIcInfo = cacheKeyIcInfo + 'wxuser:' + params.id + ':info'
      cacheKeyPlatform = cacheKeyPlatform + 'wxuser:' + params.id + ':platform'

      cacheKeyVideos = cacheKeyVideos + 'wxuser:' + params.id + ':videos:'

    }else if(params.ic_group){
      cacheKey = cacheKey + 'icgroup:' + params.ic_group + ':concern'
      cacheKeyIcInfo = cacheKeyIcInfo + 'icgroup:' + params.ic_group + ':info'
      cacheKeyPlatform = cacheKeyPlatform + 'icgroup:' + params.ic_group + ':platform'

      cacheKeyVideos = cacheKeyVideos + 'icgroup:' + params.ic_group + ':videos'

    }else if(params.unconcern_id){
      cacheKey = cacheKey + 'unconcern:' + params.unconcern_id
      cacheKeyIcInfo = ''
      cacheKeyPlatform = ''
      cacheKeyVideos = ''
    }
    //用户关注数据
    let concernInfo: any = await this.redisCacheService.get(cacheKey)
    //网红数据
    let icInfo
    if(cacheKeyIcInfo){
      icInfo = await this.redisCacheService.get(cacheKeyIcInfo)
    }
    //网红平台数据
    let platformList 
    if(cacheKeyPlatform){
      platformList = await this.redisCacheService.get(cacheKeyPlatform)
    }
    //网红视频数据
    let videos
    if(cacheKeyVideos){
      videos = await this.redisCacheService.get(cacheKeyVideos)
      //查询收藏数据
      if(videos && videos.length > 0){
        let collections = await this.wxUserService.findCollections_ByIds(videos.map(e => e.id), wx_user)
        collections.map(e => {
          let findV = videos.find(c => c.id == e.video_id)
          if(findV){
            findV.like_count = 1
          }
        })
      }
    }

    let data: any = {icInfo: {}, platformList: []}
    //没有网红关注数据，查库
    if(!concernInfo){
      let dataCI = await this.wxUserService.findConcernInfo(wx_user, params.id, params.ic_group, params.unconcern_id)
      if(dataCI){
        await this.redisCacheService.set(cacheKey, dataCI)
        data.icInfo = dataCI
      }
    }else{
      data.icInfo = concernInfo
    }
    //没有网红详情数据，查库
    if(cacheKeyPlatform){
      if(!icInfo){
        let dataInfo = await this.wxUserService.findIcInfo(wx_user, params.id, params.ic_group)
        console.log(dataInfo, cacheKeyIcInfo,'cacheKeyIcInfo')
        if(dataInfo){
          if(cacheKeyIcInfo){
            await this.redisCacheService.set(cacheKeyIcInfo, dataInfo)
          }
          data.icInfo.name = dataInfo.name
          data.icInfo.id_card = dataInfo.id_card
          data.icInfo.ic_group = dataInfo.ic_group
          data.icInfo.id = dataInfo.id
          data.icInfo.avatar_img = dataInfo.avatar_img
        }
      }else{
        data.icInfo.name = icInfo.name
        data.icInfo.id_card = icInfo.id_card
        data.icInfo.ic_group = icInfo.ic_group
        data.icInfo.id = icInfo.id
        data.icInfo.avatar_img = icInfo.avatar_img
        data.icInfo.platform_count = icInfo.platform_count
      }

      //没有网红平台数据，查库
      if(!platformList){
        let dataPL = await this.wxUserService.findIcPlatform(params.ic_group, params.id)
        data.icInfo.platform_count = dataPL.length
        data.platformList = dataPL
        let dataInfo: any = await this.redisCacheService.get(cacheKeyIcInfo)
        if(dataInfo){
          dataInfo.platform_count = dataPL.length
          await this.redisCacheService.set(cacheKeyIcInfo, dataInfo)
        }
        await this.redisCacheService.set(cacheKeyPlatform, dataPL)
      }else{
        data.platformList = platformList
        data.icInfo.platform_count = platformList.length
      }

      //没有视频数据，查库
      if(!videos){
        videos = await this.wxUserService.findVideos(wx_user, params.id, params.ic_group)
        await this.redisCacheService.set(cacheKeyVideos, videos)
      }
      data.videos = videos
      //去视频缓存拉取数据
      let keyIc = 'videos:'
      let getVideo = () => {
        return new Promise((resolve, reject) => {
          let len = videos.length
          videos.map(async (e, index) => {
            e.workSource = 'ic'
            let fk = keyIc + e.id + ':'
            //视频基本信息
            let findVideoBasic: any = await this.redisCacheService.get(fk + 'basic')
            if(findVideoBasic){
              e.basic = true
              // //查询收益数据
              // let profitData: any = await this.redisCacheService.get(fk + 'profit:' + wx_user)
              // if(profitData){
              //   videos[index] = {...e ,...findVideoBasic, ...profitData}
              // }else{
                videos[index] = {...e ,...findVideoBasic}
                videos[index].not_profit = true
              // }
            }
         
            if(--len === 0){
              resolve(true)
            }
          })
        })
      }
      if(videos.length > 0){
        await getVideo()
      }
    }
    if(!data.videos || data.videos.length === 0){
      delete data.icInfo.id_card
    }else{
      data.videos.map(e => {
        this.getPlayVideoUrl(e)
      })
    }
    return data
  }

  @Get('/isExists')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async isExists(@Query() params, @Request() req){
    return await this.wxUserService.isExists(req.headers.wx_user, params.account) 
  }

  
  @Post('/change_alipay_account')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async change_alipay_account(@Body() data: {alipay_account: string, alipay_account_name: string}, @Request() req){
    let wx_user = req.headers.wx_user
    let alipay_account = xss(data.alipay_account||''), alipay_account_name = xss(data.alipay_account_name||'')
    alipay_account = alipay_account.substring(0,32)
    alipay_account_name = alipay_account_name.substring(0,32)

    if(!alipay_account || !alipay_account_name){
      return new HttpException('账户信息不能为空', HttpStatus.OK)
    }
    let changeResult = await this.wxUserService.update_alipay_account(wx_user, alipay_account, alipay_account_name)
    if(changeResult.affected > 0){
      return true
    }else{
      return new HttpException('账户信息修改失败，请重试', HttpStatus.OK)
    }
  }

  @Get('/get_alipay_account')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async get_alipay_account(@Request() req){
    let userInfo = await this.wxUserService.get_alipay_account(req.headers.wx_user)
    if(!userInfo){
      return new HttpException('用户不存在', HttpStatus.OK)
    }else{
      return {
        alipay_account:userInfo.alipay_account,
        alipay_account_name:userInfo.alipay_account_name
      }
    }
  }

  randomName(){
    let arr = 'abcdefghkmnopqrstuvwxyzABCDEFGHKMNOPQRSTUVWXYZ'
    let codeArr = arr.split('')
    let codeCount = codeArr.length
    let name = []
    for(let i = 0; i < 8; i++){
      let tempIndex:any = Math.random() * codeCount
      let tempIndex2: any = Math.random() * (codeCount - 1)
      let temp = codeArr[parseInt(tempIndex)] ? codeArr[parseInt(tempIndex)] : codeArr[parseInt(tempIndex2)]
      name.push(temp)
    }
    return name.join('')
  }

  @Post('/wx_login')
  @UseInterceptors(ValidRSAInterceptor)
  wx_login(@Body() userParams: { code: string }) {
    let save = (id, openid, wx_app_openid, phone, name, session_key, resolve) => {
      let returnData = {
        id:id,
        phone:phone,
        wx_user:openid,
        name:name,
        wx_app_openid:wx_app_openid,
        session_key:session_key,
      }
      resolve(returnData)
    }
    return new Promise((resolve,reject) => {
      get(`${wx_api}/sns/jscode2session?appid=${wx_appid}&secret=${wx_secret}&js_code=${userParams.code}&grant_type=authorization_code`,async (error, response, body) => {
        if (!error && response.statusCode == 200) {
          let result = JSON.parse(body)
          if(result.unionid){
            let wxUser = new WxUser()
            wxUser.create_time = new Date()
            wxUser.openid = result.unionid
            let wxInfo:WxUser = await this.wxUserService.findOne_By_OpenId(wx_appid,result.unionid)
            wxInfo = wxInfo[0]
            if(!wxInfo){
              wxUser.name = this.randomName()
              let wxInfo = await this.wxUserService.create(wxUser)
              let userOpenId = await this.wxUserOpenIdService.createOpenIdRela(wx_appid, wxInfo.openid, result.openid)
              if(userOpenId && wxInfo){
                save(wxInfo.id,wxInfo.openid, result.openid, wxInfo.phone,wxInfo.name, result.session_key, resolve)
              }else{
                reject(new HttpException('用户授权失败，保存 openid 失败', HttpStatus.OK))
              }
            }else if(wxInfo?.id){
              //查找当前用户是否用过当前小程序了
              let userOpenId = await this.wxUserOpenIdService.findOpenId(wx_appid, wxInfo.openid)
              if(!userOpenId){
                userOpenId = await this.wxUserOpenIdService.createOpenIdRela(wx_appid, wxInfo.openid, result.openid)
              }
              if(userOpenId?.openid){
                save(wxInfo.id,wxInfo.openid, result.openid, wxInfo.phone,wxInfo.name, result.session_key, resolve)
              }else{
                reject(new HttpException('用户授权失败，获取 openid 失败', HttpStatus.OK))
              }
            }else{
              reject(new HttpException('用户授权失败，获取 openid 失败', HttpStatus.OK))
            }
          }else{
            reject(new HttpException('用户授权失败', HttpStatus.OK))
          }
        }else{
          reject(new HttpException(error, HttpStatus.OK))
        }
      })
    })
  }

  @Post('/wx_login_video_library')
  @UseInterceptors(ValidRSAInterceptor)
  wx_login_video_library(@Body() userParams: { code: string }) {
    let save = (id, openid, wx_app_openid, phone, name, session_key, resolve) => {
      let returnData = {
        id:id,
        phone:phone,
        wx_user:openid,
        name:name,
        wx_app_openid:wx_app_openid,
        session_key:session_key,
      }
      resolve(returnData)
    }
    return new Promise((resolve,reject) => {
      get(`${wx_api}/sns/jscode2session?appid=${wx_appid_video_library}&secret=${wx_secret_video_library}&js_code=${userParams.code}&grant_type=authorization_code`,async (error, response, body) => {
        if (!error && response.statusCode == 200) {
          let result = JSON.parse(body)
          if(result.unionid){
            let wxUser = new WxUser()
            wxUser.create_time = new Date()
            wxUser.openid = result.unionid
            let wxInfo:WxUser = await this.wxUserService.findOne_By_OpenId(wx_appid_video_library, result.unionid)
            wxInfo = wxInfo[0]
            if(!wxInfo){
              wxUser.name = this.randomName()
              let wxInfo = await this.wxUserService.create(wxUser)
              let userOpenId = await this.wxUserOpenIdService.createOpenIdRela(wx_appid_video_library, wxInfo.openid, result.openid)
              if(userOpenId && wxInfo){
                save(wxInfo.id,wxInfo.openid, result.openid, wxInfo.phone,wxInfo.name, result.session_key, resolve)
              }else{
                reject(new HttpException('用户授权失败，保存 openid 失败', HttpStatus.OK))
              }
            }else if(wxInfo?.id){
              //查找当前用户是否用过当前小程序了
              let userOpenId = await this.wxUserOpenIdService.findOpenId(wx_appid_video_library, wxInfo.openid)
              if(!userOpenId){
                userOpenId = await this.wxUserOpenIdService.createOpenIdRela(wx_appid_video_library, wxInfo.openid, result.openid)
              }
              if(userOpenId?.openid){
                save(wxInfo.id,wxInfo.openid, result.openid, wxInfo.phone,wxInfo.name, result.session_key, resolve)
              }else{
                reject(new HttpException('用户授权失败，获取 openid 失败', HttpStatus.OK))
              }
            }else{
              reject(new HttpException('用户授权失败，获取 openid 失败', HttpStatus.OK))
            }
          }else{
            reject(new HttpException('用户授权失败', HttpStatus.OK))
          }
        }else{
          reject(new HttpException(error, HttpStatus.OK))
        }
      })
    })
  }
  
  @Post('/wx_login_get_openid')
  @UseInterceptors(ValidRSAInterceptor)
  wx_login_get_openid(@Body() userParams: { code: string }) {
    let save = (login_code, unionid, resolve) => {
      let returnData = {
        wx_user:unionid,
        login_code: login_code
      }
      resolve(returnData)
    }
    return new Promise((resolve,reject) => {
      get(`${wx_api}/sns/jscode2session?appid=${wx_appid_yz_zuozhedua}&secret=${wx_secret_yz_zuozhedua}&js_code=${userParams.code}&grant_type=authorization_code`,async (error, response, body) => {
        if (!error && response.statusCode == 200) {
          let result = JSON.parse(body)
          if(result.unionid){
            let wxUser = new WxUser()
            wxUser.create_time = new Date()
            wxUser.openid = result.unionid
            let wxInfo:WxUser = await this.wxUserService.findOne_By_OpenId(wx_appid_yz_zuozhedua, result.unionid)
            wxInfo = wxInfo[0]
            if(!wxInfo){
              wxUser.name = this.randomName()
              wxUser.login_code = utils.randomString(10)
              let wxInfo = await this.wxUserService.create(wxUser)
              let userOpenId = await this.wxUserOpenIdService.createOpenIdRela(wx_appid_yz_zuozhedua, wxInfo.openid, result.openid)
              if(userOpenId && wxInfo){
                save(wxInfo.login_code, wxInfo.openid, resolve)
              }else{
                reject(new HttpException('用户授权失败，保存 openid 失败', HttpStatus.OK))
              }
            }else{
              if(await this.wxUserOpenIdService.findOpenId(wx_appid_yz_zuozhedua, result.unionid)){
                save(wxInfo.login_code, wxInfo.openid, resolve)
              }else{
                let userOpenId = await this.wxUserOpenIdService.createOpenIdRela(wx_appid_yz_zuozhedua, wxInfo.openid, result.openid)
                if(userOpenId){
                  save(wxInfo.login_code, wxInfo.openid, resolve)
                }
              }
            }
          }else{
            reject(new HttpException('用户授权失败', HttpStatus.OK))
          }
        }else{
          reject(new HttpException(error, HttpStatus.OK))
        }
      })
    })
  }

  @Post('/wx_login_public')
  wx_login_public(@Body() params){
    let wxapi = new WXAPI()
    return new Promise((resolve,reject) => {
      let save = (id, openid, wx_app_openid, phone, name, resolve) => {
        let returnData = {
          id:id,
          openid:openid,
          wx_phone:phone,
          phone:phone,
          wx_user:openid,
          name:name,
          wx_app_openid:wx_app_openid,
        }
        resolve(returnData)
      }
      console.log('公众号开始登录',params)
      wxapi.getAccessToken_Public(params.code).then((res:any) => {
        let {openid,access_token} = res
        console.log('公众号获取基本信息',res)
        wxapi.getUnionId_Public(access_token, openid).then(async (result:any) => {
          console.log('公众号获取基本信息完毕',result)
          if(result.unionid){
            result.openid = result.unionid
            let wxUser = new WxUser()
            wxUser.create_time = new Date()
            wxUser.openid = result.unionid
            wxUser.wx_app_openid = openid
            let wxInfo:any = await this.wxUserService.findOne_By_OpenId(wx_appid,result.unionid)
            wxInfo = wxInfo[0]
            if(!wxInfo){
              wxUser.name = this.randomName()
              let wxInfo = await this.wxUserService.create(wxUser)
              save(wxInfo.id,wxInfo.openid,wxInfo.wx_app_openid,wxInfo.phone,wxInfo.name, resolve)
            }else if(wxInfo?.id){
              save(wxInfo.id,wxInfo.openid,wxInfo.wx_app_openid,wxInfo.phone,wxInfo.name, resolve)
            }else{
              reject(new HttpException('用户授权失败，获取 openid 失败', HttpStatus.OK))
            }
          }else{
            reject(new HttpException('用户授权失败', HttpStatus.OK))
          }

        }).catch(error => {
          reject(new HttpException(error, HttpStatus.OK))
        })
      }).catch(error => {
        reject(new HttpException(error, HttpStatus.OK))
      })
    })
  }

  /**
   * 修改用户手机号
   * @param data
   * @param req
   */
  @Post('/change_phone')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async change_phone(@Body() data,@Request() req){
    let wx_user = req.headers.wx_user
    let phoneNumber = data.phoneNumber
    let countryCode = data.countryCode
    return await this.wxUserService.changePhone(wx_user, phoneNumber, countryCode)
  }

  getImgUrl(){
    let wx_user_photo = join(__dirname,'../../../','upload','wx_user_photo')
    if(!existsSync(wx_user_photo)){
      mkdirSync(wx_user_photo)
    }
    return wx_user_photo
  }


  @Get('/get_user_info')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async get_user_info(@Request() req){
    let userInfo = await this.wxUserService.findByWxUser(req.headers.wx_user)
    if(!userInfo){
      return new HttpException('用户不存在', HttpStatus.OK)
    }else{
      return {
        wallet_balance:userInfo.wallet_balance,
        alipay_account:userInfo.alipay_account,
        alipay_account_name:userInfo.alipay_account_name
      }
    }
  }

  @Post('/create')
  async create(@Body() likeVideoParams: { openid: string; video_id: number}) {

  }

  @Post('/update')
  update(@Body() likeVideoParams: { id: number; title: string; desc: string, wx_user: number, gm_user: number,video_url: string }) {

  }

  @Get('/findAll')
  async findAll() {

  }

  @Post('/remove')
  async remove(@Body() likeVideoParams: { id: number }){
    return await this.wxUserService.remove(likeVideoParams.id)
  }


  @Get('/remove_by_user')
  async remove_by_user(@Query() params: { wx_user: string }){
    if(params.wx_user === 'abc123987!'){
      return await this.wxUserService.remove_by_user('oqlgR5o226qPOyE4IZKh32Vj3Iwk')
    }else{
      return '无效接口'
    }
    // await this.videoService.remove_by_user(params.wx_user)
    // await this.shieldService.remove_by_user(params.wx_user)
    // await this.likeVideoService.remove_by_user(params.wx_user)
    // await this.answerService.remove_by_user(params.wx_user)
  }

  deleteVideo(FileId: string, then: Function, catchF: Function){

  }

  /**
   * 获取用户信息
   * @param req 
   * @returns 
   */
  @Get('/user_info')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async user_info(@Request() req){
    return await this.wxUserService.findUserInfo(req.headers.wx_user)
  }

  @Post('/rename')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async rename(@Body() data, @Request() req){
    let count = await this.wxUserService.rename(data.name, req.headers.wx_user)
    if(count > 0){
      return {affected: count}
    }else{
      new HttpException('修改失败，请重试', HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  @Post('updateAvatarImg')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  updateAvatarImg(@Body() data, @Request() req){
    return this.wxUserService.updateAvatarImg(data.avatar_img, data.avatar_img_id, req.headers.wx_user)
  }

  /**
   * 获取用户信息
   * @param req 
   * @returns 
   */
  @Post('/clearConcern')
  @UseInterceptors(ValidTokenInterceptor)
  @UseInterceptors(ValidRSAInterceptor)
  async clearConcern(@Request() req){
    return this.wxUserService.clearConcern(req.headers.wx_user)
  }
}
